package com.kakarote.admin.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kakarote.admin.common.AdminCodeEnum;
import com.kakarote.admin.common.PwdUtil;
import com.kakarote.admin.entity.BO.*;
import com.kakarote.admin.entity.PO.*;
import com.kakarote.admin.entity.VO.*;
import com.kakarote.admin.service.*;
import com.kakarote.admin.service.impl.AdminUserServiceImpl;
import com.kakarote.common.log.annotation.OperateLog;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.entity.OperationResult;
import com.kakarote.common.log.enums.ApplyEnum;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.common.log.enums.OperateObjectEnum;
import com.kakarote.common.log.enums.OperateTypeEnum;
import com.kakarote.core.common.ApiExplain;
import com.kakarote.core.common.MultipartFileUtil;
import com.kakarote.core.common.ParamAspect;
import com.kakarote.core.common.Result;
import com.kakarote.core.entity.*;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.exception.NoLoginException;
import com.kakarote.core.feign.admin.entity.AdminUserInfo;
import com.kakarote.core.feign.admin.entity.SimpleUser;
import com.kakarote.core.utils.UserCacheUtil;
import com.kakarote.core.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-04-27
 */
@RestController
@RequestMapping("/adminUser")
@Api(tags = "员工管理相关接口")
public class AdminUserController {

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private IAdminFileService adminFileService;

    @Autowired
    private IAdminLanguagePackService iAdminLanguagePackService;

    @Autowired
    private IAdminRoleService adminRoleService;

    @Autowired
    private IAdminSubsidiaryDeptService adminSubsidiaryDeptService;


    @Autowired
    private IAdminCompanySecuritySettingService securitySettingService;

    @Autowired
    private IAdminConfigService adminConfigService;

    @Autowired
    private IAdminUserPwdHistoryService pwdHistoryService;

    /**
     * 2代表不查询禁用员工
     **/
    private static final int TYPE = 2;

    @PostMapping("/findByUsername")
    @ApiOperation(value = "通过name查询用户", httpMethod = "POST")
    public Result<List<AdminUserInfo>> findByUsername(String username, HttpServletRequest request) {
        List<AdminUserInfo> userInfoList = adminUserService.findByUsername(username, null, request);
        return Result.ok(userInfoList);
    }



    @RequestMapping("/getIdByUserName")
    @ApiOperation(value = "通过name查询用户", httpMethod = "POST")
    public Result<Long> getIdByUserName(@RequestParam("userName") String username) {
        Optional<AdminUser> adminUserOptional = adminUserService.lambdaQuery().select(AdminUser::getUserId).eq(AdminUser::getUsername, username).oneOpt();
        return Result.ok(adminUserOptional.map(AdminUser::getUserId).orElse(0L));
    }




    @RequestMapping("/getIdByRealName")
    @ApiOperation(value = "通过name查询用户", httpMethod = "POST")
    public Result<Long> getIdByRealName(@RequestParam("userName") String username, @RequestParam(required = false, name = "companyId") Long companyId) {
        Optional<AdminUser> adminUserOptional = adminUserService.lambdaQuery().select(AdminUser::getUserId).eq(AdminUser::getRealname, username)
                .oneOpt();
        return Result.ok(adminUserOptional.map(AdminUser::getUserId).orElse(0L));
    }

    @RequestMapping("/getWxUserIdVagueRealName")
    @ApiOperation(value = "通过name模糊查询用户", httpMethod = "POST")
    public Result<JSONObject> getWxUserIdVagueRealName(@RequestParam(name = "realname", required = false) String realname, @RequestParam(name = "cursor", required = false) String cursor) {
        JSONObject jsonObject = new JSONObject();
        String nextCursor = null;
        List<AdminUserInfo> mapList = new ArrayList<>();

        jsonObject.fluentPut("list", mapList).fluentPut("nextCursor", nextCursor);
        return Result.ok(jsonObject);
    }


    @ApiOperation("通过条件分页查询员工列表")
    @PostMapping("/queryUserList")
    public Result<BasePage<AdminUserVO>> queryUserList(@RequestBody AdminUserBO adminUserBO) {
        return Result.ok(adminUserService.queryUserList(adminUserBO));
    }

    @ApiOperation("查询是否是系统项目管理员角色")
    @PostMapping("/queryProjectMangerUser")
    public Result<Boolean> queryUserList() {
        AdminUserBO adminUserBO = new AdminUserBO();
        AdminRole adminRole = adminRoleService.lambdaQuery().eq(AdminRole::getRoleType, 1).eq(AdminRole::getLabel, 2).one();
        adminUserBO.setRoleId(adminRole.getRoleId());
        adminUserBO.setPageType(0);
        BasePage<AdminUserVO> basePage = adminUserService.queryUserList(adminUserBO);
        Boolean flag = false;
        for (AdminUserVO adminUserVO : basePage.getList()) {
            if (ObjectUtil.equal(adminUserVO.getUserId(), UserUtil.getUserId())) {
                flag = true;
            }
        }
        return Result.ok(flag);
    }

    @ApiOperation("查询员工状态人数")
    @PostMapping("/countNumOfUser")
    public Result<JSONObject> countUserByLabel() {
        return Result.ok(adminUserService.countUserByLabel());
    }

    @ApiExplain("通过条件分页查询员工列表")
    @PostMapping("/queryAllUserList")
    public Result<List<Long>> queryAllUserList(@RequestParam(value = "type", required = false) Integer type) {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AdminUser::getUserId);
        /* type=2代表不查询禁用员工 */
        if (Objects.equals(TYPE, type)) {
            queryWrapper.ne(AdminUser::getStatus, 0);
        }
        return Result.ok(adminUserService.listObjs(queryWrapper, TypeUtils::castToLong));
    }

    @ApiExplain("通过条件分页查询员工列表")
    @PostMapping("/queryAllUserInfoList")
    public Result<List<UserInfo>> queryAllUserInfoList() {
        List<UserInfo> userInfoList = adminUserService.queryAllUserInfoList();
        return Result.ok(userInfoList);
    }

    @PostMapping("/setUser")
    @ApiOperation("修改用户")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, behavior = BehaviorEnum.UPDATE, type = OperateTypeEnum.SETTING)
    public Result setUser(@RequestBody AdminUserVO adminUserVO) {
        OperationLog operationLog = adminUserService.setUser(adminUserVO);
        return OperationResult.ok(operationLog);
    }

    @PostMapping("/setUserDept")
    @ApiOperation("批量修改用户部门")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.RESET)
    public Result setUserDept(@RequestBody AdminUserBO adminUserBO) {
        List<OperationLog> operationLogList = adminUserService.setUserDept(adminUserBO);
        return OperationResult.ok(operationLogList);
    }

    @PostMapping("/addUser")
    @ApiOperation("新增用户")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, behavior = BehaviorEnum.SAVE, type = OperateTypeEnum.SETTING)
    public Result addUser(@RequestBody AdminUserVO adminUserVO) {
        JSONObject data = adminUserService.addUser(adminUserVO);

        Object user = data.get("user");
        OperationLog operationLog = (OperationLog) data.get("operationLog");

        return OperationResult.ok(user, ListUtil.toList(operationLog));
    }

    @PostMapping("/usernameEdit")
    @ApiOperation("重置登录账号")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, behavior = BehaviorEnum.RESET, type = OperateTypeEnum.SETTING)
    public Result<Integer> usernameEdit(@RequestParam("id") Long id, @RequestParam("username") String username, @RequestParam("password") String password) {
        OperationLog operationLog = adminUserService.usernameEdit(id, username, password);
        return OperationResult.ok(ListUtil.toList(operationLog));
    }

    @PostMapping("/excelImport")
    @ApiOperation("excel导入员工")
    @OperateLog(apply = ApplyEnum.ADMIN, behavior = BehaviorEnum.EXCEL_IMPORT, type = OperateTypeEnum.IMPORT, object = OperateObjectEnum.USER)
    public Result<JSONObject> excelImport(@RequestParam("file") MultipartFile file) {
        JSONObject object = adminUserService.excelImport(file);

        UploadEntity uploadEntity = adminFileService.uploadTempFile(file, null);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject("uploadData", uploadEntity.getFileId());
        operationLog.setOperationObject("name", "员工");

        JSONObject info = new JSONObject();
        info.put("count", object.getInteger("totalSize"));
        info.put("errorSize", object.getInteger("errSize"));
        info.put("errorFile", object.getString("token"));
        operationLog.setOperationInfo(info.toJSONString());


        return OperationResult.ok(object, ListUtil.toList(operationLog));
    }

    @PostMapping("/downloadExcel")
    @ApiOperation("下载导入模板")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        adminUserService.downloadExcel(response);
    }

    @PostMapping("/downExcel")
    @ApiOperation("excel下载错误数据")
    public void downExcel(@RequestParam("token") String token, HttpServletResponse response) {
        String path = FileUtil.getTmpDirPath() + "/" + token;
        if (FileUtil.exist(path)) {
            File file = FileUtil.file(path);
            final String fileName = file.getName();
            final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream");
            BufferedInputStream in = null;
            try {
                in = FileUtil.getInputStream(file);
                ServletUtil.write(response, in, contentType, "import_error.xls");
            } finally {
                IoUtil.close(in);
            }
            FileUtil.del(path);
        }
    }

    @PostMapping("/hrmAddUser")
    @ApiOperation("从人力资源添加员工")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.SAVE)
    public Result hrmAddUser(@RequestBody HrmAddUserBO hrmAddUserBO) {
        List<OperationLog> operationLogList = adminUserService.hrmAddUser(hrmAddUserBO);
        return OperationResult.ok(operationLogList);
    }

    @PostMapping("/setUserStatus")
    @ApiOperation("禁用启用")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, type = OperateTypeEnum.SETTING)
    public Result setUserStatus(@RequestBody AdminUserStatusBO adminUserStatusBO) {
        List<OperationLog> operationLogList = adminUserService.setUserStatus(adminUserStatusBO);
        return OperationResult.ok(operationLogList);
    }

    @PostMapping("/confirmAgreeBook")
    @ApiOperation("确认同意书")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, type = OperateTypeEnum.SETTING)
    public Result confirmAgreeBook(@RequestBody AdminUserStatusBO adminUserStatusBO) {
        List<OperationLog> operationLogList = adminUserService.setUserStatus(adminUserStatusBO);
        return OperationResult.ok(operationLogList);
    }


    @PostMapping("/activateUser")
    @ApiOperation("激活账号")
    public Result activateUser(@RequestBody AdminUserStatusBO adminUserStatusBO) {
        adminUserService.setUserStatus(adminUserStatusBO);
        return Result.ok();
    }

    @PostMapping("/resetPassword")
    @ApiOperation("重置密码")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.EMPLOYEE_DEPARTMENT_MANAGEMENT, behavior = BehaviorEnum.RESET, type = OperateTypeEnum.SETTING)
    public Result resetPassword(@RequestBody AdminUserStatusBO adminUserStatusBO) {
        List<OperationLog> operationLogList = adminUserService.resetPassword(adminUserStatusBO);
        return OperationResult.ok(operationLogList);
    }

    @PostMapping("/updateImg")
    @ApiOperation("修改头像")
    public Result updateImg(@RequestParam("file") MultipartFile file) throws IOException {
        UploadEntity img = adminFileService.upload(file, null, "img", 0);
        AdminUser byId = adminUserService.getById(UserUtil.getUserId());
        byId.setImg(img.getUrl());
        adminUserService.updateById(byId);
        //清空用户缓存
        adminUserService.clearUserCache(byId.getUserId());
        return Result.ok(img.getFileId());
    }

    @PostMapping("/updatePicture")
    @ApiOperation("修改头像")
    public Result updatePicture(@RequestBody Map<String, Object> map) {
        String base64String = (String) map.get("base");
        String contentType = base64String.split(";")[0].split(":")[1];
        // 解码base64字符串 （如果base64有前缀如：data:image/jpg;base64,则需要去掉前缀，我这里有前缀，所以需要去掉）
        //有前缀
        byte[] decode = Base64.getDecoder().decode(base64String.split(",")[1]);
        //无前缀
//        byte[] decode = Base64.getDecoder().decode(base64String);
        // 创建字符串
        String name = "user_img" +  ".png"; // 文件名
        MultipartFileUtil.MockMultipartFile userImg = new MultipartFileUtil.MockMultipartFile("user_img", name, contentType, decode);
        UploadEntity img = adminFileService.upload(userImg, null, "img", 0);
        AdminUser byId = adminUserService.getById(UserUtil.getUserId());
        byId.setImg(img.getUrl());
        adminUserService.updateById(byId);
        //清空用户缓存
        adminUserService.clearUserCache(byId.getUserId());
        return Result.ok(img.getFileId());
    }

    @PostMapping("/updateAvatar")
    @ApiOperation("修改头像")
    public Result updateImg(@RequestParam("file") MultipartFile file,@RequestParam("userId") Long userId) throws IOException {
        if (userId==null){
            return Result.error(AdminCodeEnum.ADMIN_DATA_EXIST_ERROR);
        }
        UploadEntity img = adminFileService.upload(file, null, "img", 0);
        AdminUser byId = adminUserService.getById(userId);
        byId.setImg(img.getUrl());
        adminUserService.updateById(byId);
        //清空用户缓存
        adminUserService.clearUserCache(byId.getUserId());
        return Result.ok(img.getFileId());
    }

    @RequestMapping("/updateAvatarPath")
    @ApiOperation("修改头像路径")
    public Result updateUserAvatarByUserName(@RequestParam("userName") String userName,@RequestParam(name = "img",required = false) String img){
        adminUserService.lambdaUpdate().eq(AdminUser::getUsername,userName).set(AdminUser::getImg,img).update();
        return Result.ok();
    }

    @PostMapping("/updatePassword")
    @ApiOperation("修改登录密码")
    public Result updatePassword(@RequestParam("oldPwd") String oldPass, @RequestParam("newPwd") String newPass) {
        AdminUser adminUser = adminUserService.getById(UserUtil.getUserId());
        if (!UserUtil.verify(adminUser.getUsername() + oldPass, adminUser.getSalt(), adminUser.getPassword())) {
            return Result.error(AdminCodeEnum.ADMIN_PASSWORD_ERROR);
        }
        AdminCompanySecuritySettingVO securitySettingVO = securitySettingService.queryByConfigType(1);
        //密码强度校验
        PwdUtil.checkPwdReg(securitySettingVO.getPwdCharRequire(), newPass, securitySettingVO.getMinimumPwdLen());
        String newPwd = UserUtil.sign((adminUser.getUsername().trim() + newPass.trim()), adminUser.getSalt());
        //校验密码历史
        AdminUserPwdHistory pwdHistoryEntity = pwdHistoryService.getById(adminUser.getUserId());
        if (ObjectUtil.isNull(pwdHistoryEntity)) {
            pwdHistoryEntity = new AdminUserPwdHistory();
            pwdHistoryEntity.setUserId(adminUser.getUserId());
            pwdHistoryService.save(pwdHistoryEntity);
        }
        if (AdminUserServiceImpl.checkPwdHistory(pwdHistoryEntity.getPwdHistory(), adminUser.getPassword(),
                newPwd, securitySettingVO)) {
            throw new CrmException(AdminCodeEnum.ADMIN_PASSWORD_CHANGE_ERROR);
        }
        adminUser.setPassword(newPwd);
        adminUser.setPwdUpdStatus(1);
        String pwdHistory = AdminUserServiceImpl.handlePwdHistory(adminUser.getPassword(),
                pwdHistoryEntity.getPwdHistory(), newPwd, securitySettingVO);
        pwdHistoryEntity.setPwdHistory(pwdHistory);
        pwdHistoryService.updateById(pwdHistoryEntity);
        return updateUser(adminUser);
    }

    @PostMapping("/updateUser")
    @ApiOperation("修改用户信息")
    public Result updateUser(@RequestBody AdminUser adminUser) {
        adminUserService.updateUser(adminUser);
        return Result.ok();
    }

    @PostMapping("/queryUserNumInfo")
    @ApiOperation("查询当前用户名下的用户数量")
    @ParamAspect
    public Result<Integer> queryUserNumInfo(@ApiParam("username") @RequestParam("username") String username) {
        Long count = adminUserService.lambdaQuery().eq(AdminUser::getUsername, username).count();
        return Result.ok(count.intValue());
    }

    @PostMapping("/queryLoginUser")
    @ApiOperation("查询当前登录用户")
    public Result<AdminUserVO> queryLoginUser() {
        AdminUser user = adminUserService.getById(UserUtil.getUserId());
        if (user == null) {
            throw new NoLoginException();
        }
        AdminUserVO adminUser = BeanUtil.copyProperties(user, AdminUserVO.class);
        if (ObjectUtil.isNull(adminUser.getLastLoginTime())) {
            adminUser.setLastLoginTime(adminUser.getCreateTime());
        }
        adminUser.setIsAdmin(UserUtil.isAdmin());
        adminUser.setPassword(null);
        String deptName = UserCacheUtil.getDeptName(adminUser.getDeptId());
        adminUser.setDeptName(deptName);
        adminUser.setParentName(UserCacheUtil.getUserName(adminUser.getParentId()));
        adminUser.setLoginType(UserUtil.getUser().getLoginType());
        AdminConfig companyName = adminConfigService.queryConfigByName("companyName");
        adminUser.setCompanyName(companyName.getValue());
        return Result.ok(adminUser);
    }

    @RequestMapping("/queryUserRoleIds")
    @ApiExplain("查询用户角色列表")
    public Result<List<Long>> queryUserRoleIds(@RequestParam("userId") @NotNull Long userId) {
        return Result.ok(adminUserService.queryUserRoleIds(userId));
    }

    @RequestMapping("/queryListName")
    @ApiExplain("查询通讯录")
    public Result queryListName(@RequestBody UserBookBO userBookBO) {
        return Result.ok(adminUserService.queryListName(userBookBO));
    }

    @RequestMapping("/attention")
    @ApiExplain("切换关注状态")
    public Result attention(@RequestParam("userId") Long userId) {
        adminUserService.attention(userId);
        return Result.ok();
    }

    @RequestMapping("/queryChildUserId")
    @ApiExplain("根据用户ID下的子用户")
    public Result<List<Long>> queryChildUserId(@NotNull Long userId) {
        List<Long> longList = adminUserService.queryChildUserId(userId);
        return Result.ok(longList);
    }

    @RequestMapping("/queryUserInfo")
    @ApiOperation("查询用户信息")
    public Result<AdminUser> queryUserInfo(@RequestParam("userId") Long userId) {
        AdminUser byId = adminUserService.getById(userId);
        String nameByDeptId = UserCacheUtil.getDeptName(byId.getDeptId());
        byId.setDeptName(nameByDeptId);
        byId.setSalt(null);
        byId.setPassword(null);
        return Result.ok(byId);
    }

    @RequestMapping("/queryInfoByUserId")
    @ApiExplain("根据用户ID获取用户")
    public Result<UserInfo> queryInfoByUserId(@NotNull Long userId) {
        UserInfo userInfo = adminUserService.queryLoginUserInfo(userId);
        return Result.ok(userInfo);
    }

    @PostMapping("/queryNormalUserByIds")
    @ApiExplain("根据用户ID获取正常用户")
    public Result<List<Long>> queryNormalUserByIds(@RequestBody List<Long> ids) {
        return Result.ok(adminUserService.queryNormalUserByIds(ids));
    }

    @PostMapping("/queryUserByDeptIds")
    @ApiExplain("根据部门ID获取用户ids")
    public Result<List<Long>> queryUserByDeptIds(@RequestBody List<Long> ids) {
        List<Long> userIds = adminUserService.queryUserByDeptIds(ids);
        return Result.ok(userIds);
    }

    @PostMapping("/queryListByDeptIds")
    @ApiOperation("根据部门ID获取用户ids")
    public Result<List<SimpleUser>> queryListByDeptIds(@RequestBody List<Long> deptIds) {
        List<SimpleUser> users = adminUserService.queryListByDeptIds(deptIds);
        return Result.ok(users);
    }

    @PostMapping("/allExportExcel")
    @ApiOperation("全部导出")
    public void allExportExcel(HttpServletResponse response) {
        adminUserService.exportExcel(response, null);
    }

    @ApiOperation("选中导出")
    @PostMapping("/batchExportExcel")
    public void batchExportExcel(@RequestBody List<Long> userIds, HttpServletResponse response) {
        adminUserService.exportExcel(response, userIds);
    }

    @PostMapping("/queryAuthUserList")
    @ApiOperation("查询权限下用户")
    public Result<List<SimpleUser>> queryAuthUserList() {
        List<SimpleUser> userList = new ArrayList<>();
        if (UserUtil.isAdmin()) {
            userList.addAll(adminUserService.list().stream().map(user -> BeanUtil.copyProperties(user, SimpleUser.class)).collect(Collectors.toList()));
        } else {
            List<Long> childUserId = adminUserService.queryChildUserId(UserUtil.getUserId());
            userList.addAll(adminUserService.queryUserByIds(childUserId));
        }
        return Result.ok(userList);
    }

    @PostMapping("/queryDeptUserList/{deptId}")
    @ApiOperation("查询部门用户列表(表单使用)")
    public Result<DeptUserListVO> queryDeptUserList(@PathVariable("deptId") Long deptId) {
        DeptUserListVO deptUserListVO = adminUserService.queryDeptUserList(deptId, true);
        return Result.ok(deptUserListVO);
    }

    @PostMapping("/queryDeptUserByExamine/{deptId}")
    @ApiOperation("查询部门用户列表(审批使用)")
    public Result<DeptUserListVO> queryDeptUserByExamine(@PathVariable("deptId") Long deptId) {
        DeptUserListVO deptUserListVO = adminUserService.queryDeptUserList(deptId, false);
        return Result.ok(deptUserListVO);
    }

    @PostMapping("/queryDeptUserListByHrm")
    @ApiOperation("查询部门用户列表(hrm添加员工使用)")
    public Result<Set<HrmSimpleUserVO>> queryDeptUserListByHrm(@RequestBody DeptUserListByHrmBO deptUserListByHrmBO) {
        Set<HrmSimpleUserVO> userList = adminUserService.queryDeptUserListByHrm(deptUserListByHrmBO);
        return Result.ok(userList);
    }

    @PostMapping("/queryUserIdByRealName")
    @ApiOperation("查询用户id根据真实姓名")
    public Result<List<Long>> queryUserIdByRealName(@RequestParam("realNames") List<String> realNames) {
        List<Long> userIdList = adminUserService.queryUserIdByRealName(realNames);
        return Result.ok(userIdList);
    }

    @PostMapping("/queryUserIdByUserNameAndCompanyId")
    @ApiOperation("查询用户id根据用户名和企业id")
    public Result<Long> queryUserIdByUserNameAndCompanyId(@RequestParam("username") String username
            ) {
        Long userId = adminUserService.queryUserIdByUserNameAndCompanyId(username);
        return Result.ok(userId);
    }

    @PostMapping("/queryLoginUserInfo")
    @ApiExplain("模拟查询登陆用户信息")
    public Result<UserInfo> queryLoginUserInfo(@RequestParam("userId") Long userId) {
        UserInfo userInfo = adminUserService.queryLoginUserInfo(userId);
        return Result.ok(userInfo);
    }

    @PostMapping("/queryUserIdByUserName")
    @ApiExplain("查询用户id通过用户名")
    public Result<Long> queryUserIdByUserName(@RequestParam("userName") String userName) {
        Long userId = adminUserService.lambdaQuery().select(AdminUser::getUserId).eq(AdminUser::getUsername, userName).oneOpt().map(AdminUser::getUserId).orElse(0L);
        return Result.ok(userId);
    }

    @PostMapping("/queryUserLanguageList")
    @ApiOperation("查询用户语言列表")
    public Result<BasePage<AdminLanguagePackVO>> queryLanguageList(@RequestBody AdminLanguagePackBO adminLanguagePackBO) {
        return Result.ok(iAdminLanguagePackService.queryLanguagePackList(adminLanguagePackBO, 1));
    }

    @PostMapping("/updateUserDeflautLanguage")
    @ApiOperation("设置用户默认语言")
    public Result updateUserDeflautLanguage(@RequestParam("languagePackId") @ApiParam(name = "languagePackId", value = "languagePackId") Long id) {
        iAdminLanguagePackService.setDeflautLanguagePackSetting(id, 1);
        return Result.ok();
    }

    @PostMapping("/queryUserDeflautLanguage")
    @ApiOperation("查询用户默认语言")
    public Result<JSONObject> queryUserDeflautLanguage(@RequestBody AdminLanguagePackBO adminLanguagePackBO) {
        JSONObject jsonObject = iAdminLanguagePackService.queryDeflautLanguagePackSetting(1, adminLanguagePackBO.getLanguagePackType(), true);
        return Result.ok(jsonObject);
    }

    @PostMapping("/queryUserDeflautLanguageInfo")
    @ApiOperation("查询用户默认语言")
    public Result<JSONObject> queryUserDeflautLanguageInfo(@RequestBody AdminLanguagePackBO adminLanguagePackBO) {
        JSONObject jsonObject = iAdminLanguagePackService.queryDeflautLanguagePackSetting(1, adminLanguagePackBO.getLanguagePackType(), false);
        return Result.ok(jsonObject);
    }

    @PostMapping("/queryUserZhLanguage")
    @ApiOperation("查询用户默认中文语言")
    public Result<JSONObject> queryUserZhLanguage(@RequestBody AdminLanguagePackBO adminLanguagePackBO) {
        JSONObject jsonObject = iAdminLanguagePackService.queryUserZhLanguage(adminLanguagePackBO.getLanguagePackType(), true);
        return Result.ok(jsonObject);
    }

    @ParamAspect
    @PostMapping("/queryUserDeptOrRoleInfo")
    @ApiOperation("查询用户、角色、部门信息")
    public Result<UserInfoVO> queryUserDeptOrRoleInfo(@RequestBody UserInfoRequestBO requestBO) {
        UserInfoVO result = adminUserService.queryUserDeptOrRoleInfo(requestBO);
        return Result.ok(result);
    }

    @PostMapping("/queryParentByLevel")
    @ApiOperation("获取指定用户的上级用户")
    public Result<List<UserInfo>> queryParentByLevel(@RequestBody AdminUserQueryBO queryBO) {
        return Result.ok(adminUserService.queryParentByLevel(queryBO));
    }

    @PostMapping("/queryOrganizationInfo")
    @ApiOperation("查询完整组织架构信息")
    public Result<AdminOrganizationVO> queryOrganizationInfo() {
        AdminOrganizationVO adminOrganizationVO = adminUserService.queryOrganizationInfo();
        return Result.ok(adminOrganizationVO);
    }

    @PostMapping("/bindingWxWorkUserId")
    @ApiOperation("绑定企业微信用户id")
    public Result<SimpleUser> bindingWxWorkUserId(@RequestParam String token, @RequestParam String wxUserId) {
        return Result.ok(adminUserService.bindingWxWorkUserId(token, wxUserId));
    }

    @PostMapping("/unbindingWxWorkByUserId")
    @ApiOperation("解绑企业微信")
    public Result unbindingWxWorkByUserId(@RequestParam("userId") @NotNull Long userId) {
        adminUserService.unbindingWxWorkByUserId(userId);
        return Result.ok();
    }

    @PostMapping(value = "/queryUserListByDeptIds")
    @ApiOperation("根据部门ids查询部门以及子部门用户列表")
    public Result<List<Long>> queryUserListByDeptIds(@RequestBody List<Long> ids) {
        List<Long> userIds = adminUserService.queryUserListByDeptIds(ids);
        return Result.ok(userIds);
    }


    @PostMapping("/queryUserSubsidiaryDeptId")
    @ApiOperation("查询用户附属部门id")
    public Result<List<Long>> queryUserSubsidiaryDeptId(@RequestParam("userId") Long userId) {
        List<AdminSubsidiaryDept> list = adminSubsidiaryDeptService.lambdaQuery()
                .eq(AdminSubsidiaryDept::getUserId, userId)
                .list();
        if (CollectionUtil.isEmpty(list)) {
            return Result.ok(new ArrayList<>());
        } else {
            List<Long> collect = list.stream().map(AdminSubsidiaryDept::getDeptId).collect(Collectors.toList());
            return Result.ok(collect);
        }

    }

    @PostMapping("/resetPwdNotice")
    @ApiOperation("密码到期重置通知")
    public Result<JSONObject> resetPwdNotice() {
        return Result.ok(adminUserService.resetPwdNotice());
    }

    @PostMapping("/updateAdminUserLoginTime")
    @ApiOperation("更新最新登录系统时间")
    public Result updateAdminUserLoginTime(@RequestParam("username") String username) {
        adminUserService.updateAdminUserLoginTime(username);
        return Result.ok();
    }

    @PostMapping(value = "/getLastedLoginUser")
    @ApiOperation("查询用户信息（同一手机号在多企业下验证密码登录错误次数使用）")
    Result<Map<String, Object>> getLastedLoginUser(@RequestParam("username") String username) {
        return Result.ok(adminUserService.getLastedLoginUser(username));
    }

    @PostMapping("/forceResetPwdNotice")
    @ApiOperation("强制修改登录密码")
    public Result<JSONObject> forceResetPwdNotice() {
        return Result.ok(adminUserService.forceResetPwdNotice());
    }

    @PostMapping("/mobileSSOCheck")
    @ApiOperation("移动端免登录验证")
    public Result<JSONObject> mobileSSOCheck() {
        return Result.ok(adminUserService.mobileSSOCheck());
    }


    @RequestMapping("/getAccountInfoByUserName")
    @ApiOperation(value = "通过name查询用户账户信息", httpMethod = "POST")
    public Result<EmployeeAccountInfo> getAccountInfoByUserName(@RequestParam("userName") String username) {
        AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getUsername, username).one();
        if (adminUser != null){
            EmployeeAccountInfo employeeAccountInfo = new EmployeeAccountInfo();
            BeanUtil.copyProperties(adminUser, employeeAccountInfo);
            return Result.ok(employeeAccountInfo);
        }
        return Result.ok(new EmployeeAccountInfo());
    }
}

